<template>
  <div :class="{ hidden: hidden }" class="pagination-container">
    <el-pagination
      :background="background"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :layout="layout"
      :page-sizes="pageSizes"
      :total="total"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { defineComponent, computed } from "vue";
export default defineComponent({
  name: "Pagination",
  props: {
    total: {
      required: true,
      type: Number
    },
    page: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 10
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 20, 30, 50];
      }
    },
    layout: {
      type: String,
      default: "total, sizes, prev, pager, next, jumper"
    },
    background: {
      type: Boolean,
      default: true
    },
    hidden: {
      type: Boolean,
      default: false
    }
  },
  emits: ["update:page", "update:limit", "pagination"],
  setup(props, { emit }) {
    const currentPage = computed({
      get() {
        return props.page;
      },
      set(val) {
        emit("update:page", val);
      }
    });
    const pageSize = computed({
      get() {
        return props.limit;
      },
      set(val) {
        emit("update:limit", val);
        // 当改变size时，将页码重置为1，防止请求不到数据
        emit("update:page", 1);
      }
    });
    const handleSizeChange = val => {
      emit("pagination", { page: currentPage, limit: val });
    };
    const handleCurrentChange = val => {
      emit("pagination", { page: val, limit: pageSize });
    };

    return {
      currentPage,
      pageSize,
      handleSizeChange,
      handleCurrentChange
    };
  }
});
</script>

<style lang="scss" scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: #fff;
  padding: 10px 0;
  .hidden {
    display: none;
  }
  // 分页器icon 图标没对齐，element bug
  & :deep .el-pagination .btn-next .el-icon,
  :deep .el-pagination .btn-prev .el-icon {
    display: unset;
  }
}
</style>
